import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, QLabel

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建一个 QTableWidget
        self.tableWidget = QTableWidget(5, 3)
        self.tableWidget.setHorizontalHeaderLabels(['Column 1', 'Column 2', 'Column 3'])

        # 填充一些数据
        for row in range(5):
            for col in range(3):
                item = QTableWidgetItem(f'Item {row},{col}')
                self.tableWidget.setItem(row, col, item)

        # 连接信号
        self.tableWidget.itemSelectionChanged.connect(self.on_selection_changed)

        # 创建布局
        layout = QVBoxLayout()
        layout.addWidget(self.tableWidget)
        self.label = QLabel("Selected Data:")
        layout.addWidget(self.label)

        # 设置中心窗口
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
        self.resize(1000, 800)

    def on_selection_changed(self):
        # 获取选中的单元格
        selected_items = self.tableWidget.selectedItems()
        selected_data = [item.text() for item in selected_items]
        print(selected_data)
        self.label.setText("Selected Data: " + ", ".join(selected_data))

        # 获取选中的行和列
        selected_rows = self.tableWidget.selectionModel().selectedRows()
        selected_columns = self.tableWidget.selectionModel().selectedColumns()

        selected_row_data = [row.row() for row in selected_rows]
        selected_column_data = [f"{col.column()}" for col in selected_columns]

        print(selected_row_data)

        # self.label.setText(
        #     "Selected Data: " + ", ".join(selected_data) +
        #     "\nSelected Rows: " + ", ".join(selected_row_data) +
        #     "\nSelected Columns: " + ", ".join(selected_column_data)
        # )

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())